<?php
namespace org\crawlgenie\application\registry;
use \Logger;
use \CGException;


/**
 *  Registry class to hold application single instance objects
 *  Used more as a way to standardize object storage and access
 *
 *  $Author: jinsonxu@gmail.com $:
 *  $Date: 2014-11-16 10:39:12 +0000 (Sun, 16 Nov 2014) $:
 *  $Id: Registry.php 16 2014-11-16 10:39:12Z jinsonxu@gmail.com $:
 *  @version $Rev: 16 $:
 *  @package crawlgenie.application
 *  @subpackage registry
 */



defined('_CGEXEC') or die('Direct access not allowed');

class Registry {

    private static $registeredObjects = array();


    public static function getObj(/*string*/ $objectName) {

        if(!self::checkExists($objectName)) {
            throw new CGException($objectName
                                . ' object does not exist in Registry global array'
                                );
        } else {
            return self::$registeredObjects[$objectName];
        }

    }

    public static function addObj($object) {
        $className = get_class($object);
//        Logger::getLogger(__CLASS__)->info(__METHOD__ . ': Registry adding obj classname: ' . $className);

        if($className != __CLASS__) {
            if(!self::checkExists($className)) {
                self::$registeredObjects[$className] = $object;
            } else {
                throw new CGException('Object of type ' . $className
                                    . ' is present in Registry. Please use updateObj method instead.');
            }
        } else
        {
            throw new CGException($className . ' is not a valid Registry object candidate.');
        }
    }


    public static function updateObj($object) {
        if(class_name($object) != __CLASS__) { //avoid circular reference
            self::$registeredObjects[class_name($object)] = $object;
        }
    }


    public static function checkExists(/*string*/ $objName) {
        return (array_key_exists($objName, self::$registeredObjects)) ? true : false;
    }


    public function __toString() {
        return var_dump(self::$registeredObjects);
    }
}


?>